package com.hua.nailcampus.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hua.nailcampus.acl.mapper.FriendsMapper;
import com.hua.nailcampus.acl.mapper.MessagesMapper;
import com.hua.nailcampus.acl.mapper.UserMapper;
import com.hua.nailcampus.acl.model.Avatar;
import com.hua.nailcampus.acl.model.Friends;
import com.hua.nailcampus.acl.model.Messages;
import com.hua.nailcampus.acl.model.User;
import com.hua.nailcampus.acl.model.vo.MessagesVo;
import com.hua.nailcampus.acl.model.vo.UserDateVo;
import com.hua.nailcampus.acl.service.AvatarService;
import com.hua.nailcampus.acl.service.FriendsService;
import com.hua.nailcampus.acl.service.MessagesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author:chenjianhua
 * @Date:2023/11/15 20:03
 * @Version 17
 */
@Service
@Slf4j
public class MessagesServiceImpl extends ServiceImpl<MessagesMapper, Messages>
    implements MessagesService {

    @Autowired
    private MessagesMapper messagesMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AvatarService avatarService;

    @Autowired
    private FriendsMapper friendsMapper;

    @Override
    public List<Messages> getAllChat(Integer fromUserId, Integer toUserId) {
        List<Messages> messagesList = messagesMapper.selectList(
                new LambdaQueryWrapper<Messages>()
                        .eq(Messages::getFromUserID, fromUserId)
                        .eq(Messages::getToUserID, toUserId)
                        .eq(Messages::getBelongId,fromUserId)
                        .or()
                        .eq(Messages::getFromUserID,toUserId)
                        .eq(Messages::getToUserID,fromUserId)
                        .eq(Messages::getBelongId,fromUserId));
        log.info("取到的数据:{}",messagesList);
        return messagesList;
    }

    @Override
    public List<MessagesVo> getUnreadMessages(Integer userId) {
//        查询所有与userId相关的消息,
        List<Messages> messagesList = messagesMapper.selectList(
                new LambdaQueryWrapper<Messages>()
                        .eq(Messages::getBelongId,userId)
                        .groupBy(Messages::getId)
        );
        HashMap<Integer, Messages> map = new HashMap<>(messagesList.size());
//        遍历列表 获取到距离现在时间最近的一条消息
        for (Messages message :messagesList){
//              map中存放的是好友的ID，所以要判断发送者是自己还是好友
            if(message.getFromUserID().equals(userId)){
                map.put(message.getToUserID(), message);
            }else{
                map.put(message.getFromUserID(), message);
            }
        }
//        遍历结束之后，map中存在所有ID都是距离现在时间最近的一条消息
        List<MessagesVo> messagesVoList = new ArrayList<>();
        for(Messages messages:map.values()){
            MessagesVo messagesVo = new MessagesVo(messages);
            Integer id ;
            if(messages.getToUserID().equals(userId)){
                id = messages.getFromUserID();
            }else{
                id = messages.getToUserID();
            }
//            获取好友用户名
            User user = userMapper.selectById(id);
            Friends friends = friendsMapper.selectOne(
                    new LambdaQueryWrapper<Friends>()
                            .eq(Friends::getUId, userId)
                            .eq(Friends::getFId, user.getId()));
//            判断是否设置了对好友的昵称
            if(friends!=null){
                if(friends.getFName() != null){
                    messagesVo.setUserName(friends.getFName());
                }else{
                    messagesVo.setUserName(user.getUserName());
                }
            }
//            获取用户头像
            Avatar userAvatar = avatarService.getAvatarByUserId(id);
            if(userAvatar !=null ){
                messagesVo.setAvaUrl(userAvatar.getUrl());
            }
//            获取未读消息数量
            Long count = messagesMapper.selectCount(new LambdaQueryWrapper<Messages>()
                    .eq(Messages::getFromUserID, user.getId())
                    .eq(Messages::getToUserID, userId)
                    .eq(Messages::getStatus,false)
                    .eq(Messages::getBelongId,user.getId()));
            messagesVo.setBadgeNumber(count.intValue());
            messagesVoList.add(messagesVo);
        }
        return messagesVoList;
    }

    @Override
    public Boolean removeMessagesById(Integer userId, Integer fId) {
//      删除与好友所有聊天记录
        messagesMapper.delete(
                new LambdaQueryWrapper<Messages>()
                        .eq(Messages::getFromUserID, userId)
                        .eq(Messages::getToUserID, fId)
                        .eq(Messages::getBelongId,userId)
                        .or()
                        .eq(Messages::getFromUserID, fId)
                        .eq(Messages::getToUserID, userId)
                        .eq(Messages::getBelongId,userId)
        );
        return true;
    }

    @Override
    public void acceptMessage(Integer userId, Integer fId) {
//        查询所有与该好友消息为false的数据
        List<Messages> messagesList = messagesMapper.selectList(new LambdaQueryWrapper<Messages>()
                .eq(Messages::getFromUserID, fId)
                .eq(Messages::getToUserID, userId)
                .eq(Messages::getStatus, false)
                .eq(Messages::getBelongId,fId));
        log.info("获取到的数据：{}",messagesList);
//        若不为null,则消息接收全部更新为true
        if(messagesList!=null){
            for (Messages messages : messagesList) {
                messages.setStatus(true);
                messagesMapper.updateById(messages);
            }
        }
    }

    @Override
    public List<MessagesVo> getMessageByKeyWord(Integer userId, Integer fId, String keyWord) {
       List<Messages> messagesList = messagesMapper.selectListByKeyWord(userId,fId,keyWord);
       if(messagesList == null){
           return null;
       }
        List<MessagesVo> messagesVoList = this.messageToMessageVo(messagesList);
        return messagesVoList;
    }

    @Override
    public List<MessagesVo> getMessageByDate(Integer userId, Integer fId, String starDate, String endDate) {
        List<Messages> messagesList =  messagesMapper.selectMessageByDate(userId,fId,starDate,endDate);
        if(messagesList == null){
            return null;
        }
        List<MessagesVo> messagesVoList = this.messageToMessageVo(messagesList);
        return messagesVoList;
    }

    @Override
    public List<MessagesVo> getMessageByFromID(UserDateVo userDateVo) {
        List<Messages> messagesList = new ArrayList<>();
        Integer fromUserID = userDateVo.getSenderId();
        Integer toUserID = userDateVo.getSenderId().equals(userDateVo.getUserId())?userDateVo.getFriendId():userDateVo.getUserId();
        if(userDateVo.getStarDate() == null){
            messagesList = messagesMapper.selectList(new LambdaQueryWrapper<Messages>()
                    .eq(Messages::getFromUserID,fromUserID)
                    .eq(Messages::getToUserID,toUserID));
        }else{
           messagesList = messagesMapper.selectMessageBySenderIdAndDate(fromUserID,toUserID,userDateVo.getStarDate(),userDateVo.getEndDate());
           log.info("时间带人:{}",messagesList);
        }
        return this.messageToMessageVo(messagesList);
    }



    /**
     * 将Messages对象转换为MessagesVo对象
     * @param messagesList
     * @return
     */
    public  List<MessagesVo> messageToMessageVo(List<Messages> messagesList){
        List<MessagesVo> messagesVoList = new ArrayList<>();
        for (Messages messages : messagesList){
            MessagesVo messagesVo = new MessagesVo(messages);
            User formUser = userMapper.selectById(messages.getFromUserID());
            messagesVo.setUserName(formUser.getUserName());
            messagesVo.setToUserName(userMapper.selectById(messages.getToUserID()).getUserName());
//            判断用户是否设置了头像
            Avatar avatar = avatarService.getAvatarByUserId(messages.getFromUserID());
//            消息发送者头像
            if(avatar!=null){
                messagesVo.setAvaUrl(avatar.getUrl());
            }
            messagesVoList.add(messagesVo);
        }
        Collections.reverse(messagesVoList);
        return messagesVoList;
    }
}
